/*
 * Copyright 2005-2013 finalist.cn. All rights reserved.
 * Support: http://www.finalist.cn
 * License: http://www.finalist.cn/license
 */
package com.finalist.controller.admin;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.finalist.Message;
import com.finalist.Pageable;
import com.finalist.entity.Admin;
import com.finalist.entity.Member;
import com.finalist.entity.Order;
import com.finalist.entity.Order.InspectionStatus;
import com.finalist.entity.Order.OrderStatus;
import com.finalist.entity.Order.PaymentStatus;
import com.finalist.entity.Order.ShippingStatus;
import com.finalist.entity.OrderChildrenItem;
import com.finalist.entity.OrderItem;
import com.finalist.entity.Payment;
import com.finalist.entity.Payment.Status;
import com.finalist.entity.Payment.Type;
import com.finalist.entity.PaymentMethod;
import com.finalist.entity.Product;
import com.finalist.entity.Refunds;
import com.finalist.entity.Sn;
import com.finalist.service.AdminService;
import com.finalist.service.AreaService;
import com.finalist.service.AreaStandardCodeService;
import com.finalist.service.MemberService;
import com.finalist.service.OrderChildrenItemService;
import com.finalist.service.OrderItemService;
import com.finalist.service.OrderService;
import com.finalist.service.PaymentMethodService;
import com.finalist.service.PaymentService;
import com.finalist.service.ProductService;
import com.finalist.service.SnService;

/**
 * Controller - 订单
 * 
 * @author Finalist IT Group
 * @version 3.0
 */
@Controller("adminOrderController")
@RequestMapping("/admin/order")
public class OrderController extends BaseController
{
    private Logger log = Logger.getLogger(OrderController.class);

    @Resource(name = "adminServiceImpl")
    private AdminService adminService;
    @Resource(name = "areaServiceImpl")
    private AreaService areaService;
    @Resource(name = "productServiceImpl")
    private ProductService productService;
    @Resource(name = "orderServiceImpl")
    private OrderService orderService;
    @Resource(name = "orderItemServiceImpl")
    private OrderItemService orderItemService;
    @Resource(name = "paymentMethodServiceImpl")
    private PaymentMethodService paymentMethodService;
    @Resource(name = "snServiceImpl")
    private SnService snService;
    @Resource(name = "orderChildrenItemServiceImpl")
    private OrderChildrenItemService orderChildrenItemService;
    @Resource(name = "areaStandardCodeServiceImpl")
    private AreaStandardCodeService areaStandardCodeService;
    
    @Resource(name = "paymentServiceImpl")
    private PaymentService paymentService;

	@Resource(name = "memberServiceImpl")
	private MemberService memberService;
    
    /**
     * 检查锁定
     */
    @RequestMapping(value = "/check_lock", method = RequestMethod.POST)
    public @ResponseBody
    Message checkLock(Long id)
    {
        Order order = orderService.find(id);
        if (order == null)
        {
            return Message.warn("admin.common.invalid");
        }
        Admin admin = adminService.getCurrent();
        if (order.isLocked(admin))
        {
            if (order.getOperator() != null)
            {
                return Message.warn("admin.order.adminLocked", order.getOperator().getUsername());
            }
            else
            {
                return Message.warn("admin.order.memberLocked");
            }
        }
        else
        {
            order.setLockExpire(DateUtils.addSeconds(new Date(), 20));
            order.setOperator(admin);
            orderService.update(order);
            return SUCCESS_MESSAGE;
        }
    }

    /**
     * 查看
     */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Long id, ModelMap model)
    {
        model.addAttribute("methods", Payment.Method.values());
        model.addAttribute("refundsMethods", Refunds.Method.values());
        model.addAttribute("paymentMethods", paymentMethodService.findAll());
        Order order = orderService.find(id);
        model.addAttribute("order", order);
        String selectPhone=order.getSelectedPhone();
        return "/admin/order/view";
    }

    /**
     * 确认
     */
    @RequestMapping(value = "/confirm", method = RequestMethod.POST)
    public String confirm(Long id, RedirectAttributes redirectAttributes)
    {
        Order order = orderService.find(id);
        Admin admin = adminService.getCurrent();
        if (order != null && !order.isExpired() && order.getOrderStatus() == OrderStatus.unconfirmed && !order.isLocked(admin))
        {
            orderService.confirm(order, admin);
            addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        }
        else
        {
            addFlashMessage(redirectAttributes, Message.warn("admin.common.invalid"));
        }
        return "redirect:view.jhtml?id=" + id;
    }


    /**
     * 扫描串码验货
     */
    @RequestMapping(value = "/inputInspection", method = RequestMethod.POST)
    public @ResponseBody
    String inputInspection(Order order, RedirectAttributes redirectAttributes) {
     return "fail";
    }

    public OrderChildrenItem  updateOrderChildrenItem(Order order, OrderChildrenItem.InspectionStatus inspectionStatus) {
    	
    	/*if (!inspectionStatus.equals(OrderChildrenItem.InspectionStatus.fail)) {
    		orderChildrenItem.setSerialNo(serialNo);
    	}
    	orderChildrenItem.setInspectionStatus(inspectionStatus);
    	orderChildrenItemService.update(orderChildrenItem);
    	List<OrderChildrenItem> list = orderItem.getOrderChildrenItems();
    	
    	if (list!=null && list.size()>0 ) {
    		int successSum = 0;
    		int failSum = 0;
    		int sum = 0;
    		for (OrderChildrenItem childrenItem : list) {
				if (childrenItem.getInspectionStatus().equals(OrderChildrenItem.InspectionStatus.success)) {//
					successSum++;
				} if (childrenItem.getInspectionStatus().equals(OrderChildrenItem.InspectionStatus.fail)) {
					failSum++;
				}
				sum ++ ;
			}
    		if (successSum == sum) {
    			orderItem.setInspectionStatus(OrderItem.InspectionStatus.success);
    		}
    		if (failSum == sum) {
    			orderItem.setInspectionStatus(OrderItem.InspectionStatus.fail);
    		}
    		if (successSum > 0 &&  successSum < sum) {
    			orderItem.setInspectionStatus(OrderItem.InspectionStatus.partOfTheSuccess);
    		}
    		orderItemService.update(orderItem);
    	}
    	
    	//Order order = orderItem.getOrder();
    	if (order!=null) {
    		List<OrderItem> listOrderItems = order.getOrderItems();
    		int successSum2 = 0;
    		int failSum2 = 0;
    		int sum2 = 0;
    		for (OrderItem orderitem : listOrderItems) {
				if (orderitem.getInspectionStatus().equals(OrderItem.InspectionStatus.success)) {//
					successSum2++;
				} if (orderitem.getInspectionStatus().equals(OrderItem.InspectionStatus.fail)) {
					failSum2++;
				}
				sum2 ++ ;
			}
    		if (successSum2 == sum2) {
    			order.setInspectionStatus(Order.InspectionStatus.success);
    		}
    		if (failSum2 == sum2) {
    			order.setInspectionStatus(Order.InspectionStatus.fail);
    		}
    		if (successSum2 > 0 &&  successSum2 < sum2) {
    			order.setInspectionStatus(Order.InspectionStatus.partOfTheSuccess);
    		}
    		orderService.merge(order);
    	}*/
    	return null;
    }
    /**
     * 封装订单信息并返回当前要验货的订单商品明细信息
     * @param order
     * @param orderItemId
     * @param serialNo
     * @param inspectionStatus
     * @return
     */
   /* public OrderItem packageOrder(Long orderItemId, String serialNo, com.finalist.entity.OrderChildrenItem.InspectionStatus inspectionStatus)
    {
        OrderItem inspectionOrderItem = new OrderItem();//要验货的商品
        List<OrderItem> orderItemList = order.getOrderItems();
        if (CollectionUtils.isNotEmpty(orderItemList))
        {
            for (int i = 0; i < orderItemList.size(); i++)
            {
                long orgId = orderItemList.get(i).getId();
                if (orderItemId == orgId)
                {
                    inspectionOrderItem = orderItemList.get(i);
                    //orderItemList.get(i).setSerialNo(serialNo);
                    if (inspectionStatus != null)
                    {
                        List<OrderChildrenItem> list = orderItemList.get(i).getOrderChildrenItems();
                        
                        for (int j = 0; j < list.size(); j++) {
                        	//订单子项
							list.get(j).setInspectionStatus(inspectionStatus);
						}
                        
                    }
                    break;
                }
            }
        }
        return inspectionOrderItem;
    }*/

    /**
     * 验货
     */
    @RequestMapping(value = "/inspection", method = RequestMethod.POST)
    public String inspection(Order order, String[] productId, RedirectAttributes redirectAttributes)
    {

        Order order1 = orderService.find(order.getId());

        //组装订单信息，组装串码到订单信息中
        String resultStr = "success";//验货结果
        List<OrderItem> orderItemList = order1.getOrderItems();
        if (CollectionUtils.isNotEmpty(orderItemList))
        {
            for (OrderItem tempOrderItem : orderItemList)
            {
                if (tempOrderItem.getOrderChildrenItems().get(0).getInspectionStatus() == com.finalist.entity.OrderChildrenItem.InspectionStatus.init)
                {//未验货
                    resultStr = "init";
                }
                else if (tempOrderItem.getOrderChildrenItems().get(0).getInspectionStatus() == com.finalist.entity.OrderChildrenItem.InspectionStatus.fail)
                {//验货失败
                    resultStr = "fail";
                }
            }
        }

        if ("success".equals(resultStr))
        {
            order1.setInspectionStatus(InspectionStatus.success);
            orderService.merge(order1);
            addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        }
        else if ("fail".equals(resultStr))
        {
            order1.setInspectionStatus(InspectionStatus.fail);
            orderService.merge(order1);
            addFlashMessage(redirectAttributes, Message.warn("验货失败,存在未验货通过的商品"));
        }
        else if ("init".equals(resultStr))
        {
            order1.setInspectionStatus(InspectionStatus.fail);
            orderService.merge(order1);
            addFlashMessage(redirectAttributes, Message.warn("验货失败,存在未验货的商品"));
        }
        return "redirect:view.jhtml?id=" + order.getId();
    }

    @RequestMapping(value = "/inputInspectionResult")
    public String inputInspectionResult(Long orderItemId,  ModelMap model, RedirectAttributes redirectAttributes)
    {

    	OrderItem orderItem = orderItemService.find(orderItemId);
    	if (orderItem != null) {
    		List<OrderChildrenItem>  list = orderItem.getOrderChildrenItems();
    		model.addAttribute("orderChildrenItemList", list);
    		model.addAttribute("orderItemId", orderItem.getId());
    	}
        return "/admin/order/inputInspectionResult";
    }
    
    
    /**
     * 完成
     */
    @RequestMapping(value = "/complete", method = RequestMethod.POST)
    public String complete(Long id, RedirectAttributes redirectAttributes)
    {
        Order order = orderService.find(id);
        Admin admin = adminService.getCurrent();
        if (order != null && !order.isExpired() && order.getOrderStatus() == OrderStatus.confirmed && !order.isLocked(admin))
        {
            orderService.complete(order, admin);
            addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        }
        else
        {
            addFlashMessage(redirectAttributes, Message.warn("admin.common.invalid"));
        }
        return "redirect:view.jhtml?id=" + id;
    }

    /**
     * 取消
     */
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    public String cancel(Long id, RedirectAttributes redirectAttributes)
    {
        Order order = orderService.find(id);
        Admin admin = adminService.getCurrent();
        if (order != null && !order.isExpired() && order.getOrderStatus() == OrderStatus.unconfirmed && !order.isLocked(admin))
        {
            orderService.cancel(order, admin);
            addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        }
        else
        {
            addFlashMessage(redirectAttributes, Message.warn("admin.common.invalid"));
        }
        return "redirect:view.jhtml?id=" + id;
    }

    /**
     * 支付
     */
    @RequestMapping(value = "/payment", method = RequestMethod.POST)
    public String payment(Long orderId, Long paymentMethodId, Payment payment, RedirectAttributes redirectAttributes)
    {
        Order order = orderService.find(orderId);
        payment.setOrder(order);
        PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
        payment.setPaymentMethod(paymentMethod != null ? paymentMethod.getName() : null);
        if (!isValid(payment))
        {
            return ERROR_VIEW;
        }
        if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed)
        {
            return ERROR_VIEW;
        }
        if (order.getPaymentStatus() != PaymentStatus.unpaid && order.getPaymentStatus() != PaymentStatus.partialPayment)
        {
            return ERROR_VIEW;
        }
        if (payment.getAmount().compareTo(new BigDecimal(0)) <= 0 || payment.getAmount().compareTo(order.getAmountPayable()) > 0)
        {
            return ERROR_VIEW;
        }
        Member member = order.getMember();
        if (payment.getMethod() == Payment.Method.deposit && payment.getAmount().compareTo(member.getBalance()) > 0)
        {
            return ERROR_VIEW;
        }
        Admin admin = adminService.getCurrent();
        if (order.isLocked(admin))
        {
            return ERROR_VIEW;
        }
        payment.setSn(snService.generate(Sn.Type.payment));
        payment.setType(Type.payment);
        payment.setStatus(Status.success);
        payment.setFee(new BigDecimal(0));
        payment.setOperator(admin.getUsername());
        payment.setPaymentDate(new Date());
        payment.setPaymentPluginId(null);
        payment.setExpire(null);
        payment.setMember(null);
        orderService.payment(order, payment, admin);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:view.jhtml?id=" + orderId;
    }

    /**
     * 退款
     */
    @RequestMapping(value = "/refunds", method = RequestMethod.POST)
    public String refunds(Long orderId, Long paymentMethodId, Refunds refunds, RedirectAttributes redirectAttributes)
    {
        Order order = orderService.find(orderId);
        refunds.setOrder(order);
        PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
        refunds.setPaymentMethod(paymentMethod != null ? paymentMethod.getName() : null);
        if (!isValid(refunds))
        {
            return ERROR_VIEW;
        }
        if (order.isExpired() || order.getOrderStatus() != OrderStatus.confirmed)
        {
            return ERROR_VIEW;
        }
        if (order.getPaymentStatus() != PaymentStatus.paid && order.getPaymentStatus() != PaymentStatus.partialPayment && order.getPaymentStatus() != PaymentStatus.partialRefunds)
        {
            return ERROR_VIEW;
        }
        if (refunds.getAmount().compareTo(new BigDecimal(0)) <= 0 || refunds.getAmount().compareTo(order.getAmountPaid()) > 0)
        {
            return ERROR_VIEW;
        }
        Admin admin = adminService.getCurrent();
        if (order.isLocked(admin))
        {
            return ERROR_VIEW;
        }
        refunds.setSn(snService.generate(Sn.Type.refunds));
        refunds.setOperator(admin.getUsername());
        orderService.refunds(order, refunds, admin);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:view.jhtml?id=" + orderId;
    }



    /**
     * 编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Long id, ModelMap model)
    {
        model.addAttribute("paymentMethods", paymentMethodService.findAll());
        model.addAttribute("order", orderService.find(id));
        return "/admin/order/edit";
    }

    /**
     * 订单项添加
     */
    @RequestMapping(value = "/order_item_add", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> orderItemAdd(String productSn)
    {
        Map<String, Object> data = new HashMap<String, Object>();
        Product product = productService.findBySn(productSn);
        if (product == null)
        {
            data.put("message", Message.warn("admin.order.productNotExist"));
            return data;
        }
        if (!product.getIsMarketable())
        {
            data.put("message", Message.warn("admin.order.productNotMarketable"));
            return data;
        }
        if (product.getIsOutOfStock())
        {
            data.put("message", Message.warn("admin.order.productOutOfStock"));
            return data;
        }
        data.put("sn", product.getSn());
        data.put("fullName", product.getFullName());
        data.put("price", product.getPrice());
        data.put("weight", product.getWeight());
        data.put("isGift", product.getIsGift());
        data.put("message", SUCCESS_MESSAGE);
        return data;
    }

    /**
     * 计算
     */
    @RequestMapping(value = "/calculate", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> calculate(Order order, Long areaId, Long paymentMethodId, Long shippingMethodId)
    {
        Map<String, Object> data = new HashMap<String, Object>();
        for (Iterator<OrderItem> iterator = order.getOrderItems().iterator(); iterator.hasNext();)
        {
            OrderItem orderItem = iterator.next();
            if (orderItem == null || StringUtils.isEmpty(orderItem.getSn()))
            {
                iterator.remove();
            }
        }
        order.setArea(areaService.find(areaId));
        order.setPaymentMethod(paymentMethodService.find(paymentMethodId));
        Order pOrder = orderService.find(order.getId());
        if (pOrder == null)
        {
            data.put("message", Message.error("admin.common.invalid"));
            return data;
        }
        for (OrderItem orderItem : order.getOrderItems())
        {
            if (orderItem.getId() != null)
            {
                OrderItem pOrderItem = orderItemService.find(orderItem.getId());
                if (pOrderItem == null || !pOrder.equals(pOrderItem.getOrder()))
                {
                    data.put("message", Message.error("admin.common.invalid"));
                    return data;
                }
                Product product = pOrderItem.getProduct();
                if (product != null && product.getStock() != null)
                {
                    if (pOrder.getIsAllocatedStock())
                    {
                        if (orderItem.getQuantity() > product.getAvailableStock() + pOrderItem.getQuantity())
                        {
                            data.put("message", Message.warn("admin.order.lowStock"));
                            return data;
                        }
                    }
                    else
                    {
                        if (orderItem.getQuantity() > product.getAvailableStock())
                        {
                            data.put("message", Message.warn("admin.order.lowStock"));
                            return data;
                        }
                    }
                }
            }
            else
            {
                Product product = productService.findBySn(orderItem.getSn());
                if (product == null)
                {
                    data.put("message", Message.error("admin.common.invalid"));
                    return data;
                }
                if (product.getStock() != null && orderItem.getQuantity() > product.getAvailableStock())
                {
                    data.put("message", Message.warn("admin.order.lowStock"));
                    return data;
                }
            }
        }
        Map<String, Object> orderItems = new HashMap<String, Object>();
        for (OrderItem orderItem : order.getOrderItems())
        {
            orderItems.put(orderItem.getSn(), orderItem);
        }
        order.setFee(pOrder.getFee());
        order.setPromotionDiscount(pOrder.getPromotionDiscount());
        order.setCouponDiscount(pOrder.getCouponDiscount());
        order.setAmountPaid(pOrder.getAmountPaid());
        data.put("weight", order.getWeight());
        data.put("price", order.getPrice());
        data.put("quantity", order.getQuantity());
        data.put("amount", order.getAmount());
        data.put("orderItems", orderItems);
        data.put("message", SUCCESS_MESSAGE);
        return data;
    }

    /**
     * 更新
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(Order order, Long areaId, Long paymentMethodId, Long shippingMethodId, RedirectAttributes redirectAttributes)
    {
        for (Iterator<OrderItem> iterator = order.getOrderItems().iterator(); iterator.hasNext();)
        {
            OrderItem orderItem = iterator.next();
            if (orderItem == null || StringUtils.isEmpty(orderItem.getSn()))
            {
                iterator.remove();
            }
        }
        if(areaId!=null){
        	order.setArea(areaService.find(areaId));
        }
        if(paymentMethodId!=null){
        	order.setPaymentMethod(paymentMethodService.find(paymentMethodId));
        }
        Order pOrder = orderService.find(order.getId());
        if (pOrder == null)
        {
            return ERROR_VIEW;
        }
        if (pOrder.isExpired() || pOrder.getOrderStatus() != OrderStatus.unconfirmed)
        {
            return ERROR_VIEW;
        }
        Admin admin = adminService.getCurrent();
        if (pOrder.isLocked(admin))
        {
            return ERROR_VIEW;
        }
//        if (!order.getIsInvoice())
//        {
//            order.setInvoiceTitle(null);
//            order.setTax(new BigDecimal(0));
//        }
        for (OrderItem orderItem : order.getOrderItems())
        {
            if (orderItem.getId() != null)
            {
                OrderItem pOrderItem = orderItemService.find(orderItem.getId());
                if (pOrderItem == null || !pOrder.equals(pOrderItem.getOrder()))
                {
                    return ERROR_VIEW;
                }
                Product product = pOrderItem.getProduct();
                if (product != null && product.getStock() != null)
                {
                    if (pOrder.getIsAllocatedStock())
                    {
                        if (orderItem.getQuantity() > product.getAvailableStock() + pOrderItem.getQuantity())
                        {
                            return ERROR_VIEW;
                        }
                    }
                    else
                    {
                        if (orderItem.getQuantity() > product.getAvailableStock())
                        {
                            return ERROR_VIEW;
                        }
                    }
                }
                BeanUtils.copyProperties(pOrderItem, orderItem, new String[] { "price", "quantity" });
//                if (pOrderItem.getIsGift())
//                {
//                    orderItem.setPrice(new BigDecimal(0));
//                }
            }
            else
            {
                Product product = productService.findBySn(orderItem.getSn());
                if (product == null)
                {
                    return ERROR_VIEW;
                }
                if (product.getStock() != null && orderItem.getQuantity() > product.getAvailableStock())
                {
                    return ERROR_VIEW;
                }
                orderItem.setName(product.getName());
                orderItem.setFullName(product.getFullName());
                if (product.getIsGift())
                {
                    orderItem.setPrice(new BigDecimal(0));
                }
                orderItem.setWeight(product.getWeight());
                orderItem.setThumbnail(product.getThumbnail());
                orderItem.setIsGift(product.getIsGift());
                orderItem.setShippedQuantity(0);
                orderItem.setReturnQuantity(0);
                orderItem.setProduct(product);
                orderItem.setOrder(pOrder);
            }
        }
        order.setSn(pOrder.getSn());
        order.setOrderStatus(pOrder.getOrderStatus());
        order.setPaymentStatus(pOrder.getPaymentStatus());
        order.setShippingStatus(pOrder.getShippingStatus());
        order.setFee(pOrder.getFee());
        order.setPromotionDiscount(pOrder.getPromotionDiscount());
        order.setCouponDiscount(pOrder.getCouponDiscount());
        order.setAmountPaid(pOrder.getAmountPaid());
        order.setPromotion(pOrder.getPromotion());
        order.setExpire(pOrder.getExpire());
        order.setLockExpire(null);
        order.setIsAllocatedStock(pOrder.getIsAllocatedStock());
        order.setOperator(null);
        order.setMember(pOrder.getMember());
        order.setCouponCode(pOrder.getCouponCode());
        order.setCoupons(pOrder.getCoupons());
        order.setOrderLogs(pOrder.getOrderLogs());
        order.setPayments(pOrder.getPayments());
        order.setRefunds(pOrder.getRefunds());
        order.setReturns(pOrder.getReturns());
        order.setChildrenNum(pOrder.getChildrenNum());
        order.setAdultNum(pOrder.getAdultNum());
        order.setGoDate(new Date());
        order.setIsShareHouse(pOrder.getIsShareHouse());
        order.setAdminId(pOrder.getAdminId());
        order.setProductName(pOrder.getProductName());
        
        orderService.update(order, admin);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.jhtml";
    }

    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(OrderStatus orderStatus, String productName, PaymentStatus paymentStatus, ShippingStatus shippingStatus, Boolean hasExpired, Pageable pageable, ModelMap model)
    {
    	model.addAttribute("orderProductName", productName);
    	
        model.addAttribute("orderStatus", orderStatus);
        model.addAttribute("paymentStatus", paymentStatus);
        model.addAttribute("shippingStatus", shippingStatus);
        model.addAttribute("hasExpired", hasExpired);
        Admin admin=adminService.getCurrent();
        
        model.addAttribute("page", orderService.findPage(orderStatus, productName, paymentStatus, shippingStatus, hasExpired,admin.getAminId(), pageable));
        
		List<Product> products = productService.findProductByCondition(1, null, null, null, null, null, null, null);
		model.addAttribute("products", products);
        
        return "/admin/order/list";
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public @ResponseBody
    Message delete(Long[] ids)
    {
        if (ids != null)
        {
            Admin admin = adminService.getCurrent();
            for (Long id : ids)
            {
                Order order = orderService.find(id);
                if (order != null && order.isLocked(admin))
                {
                    return Message.error("admin.order.deleteLockedNotAllowed", order.getSn());
                }
            }
            try {
				orderService.delete(ids);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
        return SUCCESS_MESSAGE;
    }
    
    /**
     * 管理员--订单列表
     */
    @RequestMapping(value = "/showOrders", method = RequestMethod.GET)
    public String showOrders(Long id, OrderStatus orderStatus, PaymentStatus paymentStatus, ShippingStatus shippingStatus, Boolean hasExpired, Pageable pageable, ModelMap model)
    {
        model.addAttribute("orderStatus", orderStatus);
        model.addAttribute("paymentStatus", paymentStatus);
        model.addAttribute("shippingStatus", shippingStatus);
        model.addAttribute("hasExpired", hasExpired);
        
        //Admin admin = adminService.getCurrent();
        //model.addAttribute("page", orderService.findPage(orderStatus, paymentStatus, shippingStatus, hasExpired,admin.getAminId(), pageable));
        //model.addAttribute("page", orderService.find(id));
        //Order order = orderService.find(id);
        //Page<Order> order2 = orderService.findPage(orderStatus, paymentStatus, shippingStatus, hasExpired, id, pageable);
        model.addAttribute("page", orderService.findPage(orderStatus, null, paymentStatus, shippingStatus, hasExpired, id, pageable));
        return "/admin/order/list";
    }

    /**
     * 查看订单（会员管理）
     * @param id
     * @param pageable
     * @param model
     * @return
     */
    @RequestMapping(value = "/viewOrder", method = RequestMethod.GET)
    public String viewOrder(Long id, Pageable pageable, ModelMap model){
    	 Member member = memberService.find(id); 
         model.addAttribute("page", orderService.findPage(member, pageable));
    	return "/admin/order/list";
    }
}